package com.jy.wms.controller;

import com.github.pagehelper.Page;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.PropertyUtil;
import com.jy.wms.common.SetStatus;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.base.*;
import com.jy.wms.pojo.SysHz;
import com.jy.wms.pojo.WmsEstimatedArrivalOrder;
import com.jy.wms.pojo.WmsOwner;
import com.jy.wms.service.WmsEstimatedArrivalOrderDetailedService;
import com.jy.wms.service.WmsEstimatedArrivalOrderService;
import com.jy.wms.service.WmsOwnerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: WmsEstimatedArrivalOrderController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author Liyi
 * @Date Wed Sep 27 09:24:26 CST 2017
 */

/**
 * @ClassName: WmsEstimatedArrivalOrderController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author Liyi
 * @Date Tue Sep 19 10:19:48 CST 2017
 */
@Controller
@RequestMapping("/wmsEstimatedArrivalOrder")
@Api(value = "/wmsEstimatedArrivalOrder", description = "关于预期到货通知单操作")
public class  WmsEstimatedArrivalOrderController extends BaseController<WmsEstimatedArrivalOrderService,WmsEstimatedArrivalOrder> {

    @Autowired
    private WmsEstimatedArrivalOrderDetailedService wmsEstimatedArrivalOrderDetailedService;

    @Autowired
    private WmsOwnerService wmsOwnerService;

    @ApiOperation(value = "预期到货通知单 POST请求查询预期到货通知单列表",response = JSONObject.class, notes = "POST请求查询预期到货通知单列表")
    @PostMapping(value = "/list")
    public @ResponseBody
    JSONObject getWmsOwnerOrdertype(@RequestBody WmsEstimatedArrivalOrder entity, HttpSession session)  {
        JSONObject json = getJSONObject();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz = (List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            Page<WmsEstimatedArrivalOrder> list = new Page<WmsEstimatedArrivalOrder>();
            if(hz.size()>0){
                list = baseService.baseSelectPage(entity,hz.get(0).getHzid(),String.valueOf(userinfo.getUser().getOrgId().get(0)),userinfo.getUser().getOrgName(),hz.get(0).getShow_hzid());
            }
            json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
        } catch (ServiceException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @ApiOperation(value = "码盘收货列表查询 POST请求查询码盘收货列表",response = JSONObject.class, notes = "POST请求查询码盘收货列表")
    @PostMapping(value = "/seachSorting")
    public @ResponseBody JSONObject getWmsseachSorting(@RequestBody WmsEstimatedArrivalOrder entity, HttpSession session) {
        JSONObject json = getJSONObject();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz = (List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            if(hz.size()>0){
                Page<WmsEstimatedArrivalOrder> list = baseService.seachSorting
                        (entity, hz.get(0).getHzid(),String.valueOf(userinfo.getUser().getOrgId().get(0)),userinfo.getUser().getOrgName());
                json =  SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
            }
        } catch (ServiceException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @ApiOperation(value = "ASN收货列表查询 POST请求查询ASN收货列表",response = JSONObject.class, notes = "POST请求查询ASN收货列表")
    @PostMapping(value = "/seachASNReceiving")
    public @ResponseBody  JSONObject getWmsseachASNReceiving(@RequestBody WmsEstimatedArrivalOrder entity, HttpSession session) {
        JSONObject json = getJSONObject();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz = (List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            if(hz.size()>0){
                Page<WmsEstimatedArrivalOrder> list = baseService.seachASNReceiving
                        (entity,hz.get(0).getHzid(),String.valueOf(userinfo.getUser().getOrgId().get(0)),userinfo.getUser().getOrgName());
                json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
            }
        } catch (ServiceException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @PostMapping(value = "/getPoList")
    @ApiOperation(value = "预期到货通知单 分页查询PO编号列表", response = JSONObject.class, notes = "{\"page\":\"页码\",\"rows\":\"每页显示行数\",\"bh\":\"PO编号\"}")
    public @ResponseBody
    JSONObject getPoList(HttpSession session,@RequestBody Map<String,Object> map){
        JSONObject json = getJSONObject();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            Page<Map<String,Object>> list = new Page<Map<String,Object>>();
            if(hz.size()>0){
                Integer page = (Integer)map.get("page");
                Integer rows = (Integer)map.get("rows");
                String bh ="";
                if(map.containsKey("bh")){
                    bh = (String)map.get("bh");
                }
                //分页查询PO编号列表
                list = baseService.baseSelectPurchaseOrderPage(page,rows,bh,hz.get(0).getHzid(),userinfo.getUser().getOrgName());
            }
            json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
        } catch (ServiceException e){
            e.printStackTrace();
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @GetMapping(value = "/getPoDetailed/{sscgdid}")
    @ApiOperation(value = "预期到货通知单 分页查询PO明细列表", response = JSONObject.class, notes = "\"sscgdid\":\"PO对应采购订单ID\"}")
    public @ResponseBody
    JSONArray getPoDetailed(@PathVariable("sscgdid") String sscgdid){
        JSONArray json = new JSONArray();
        try {
            List<Map<String,Object>> list = baseService.getPoDetailed(sscgdid);
            if(list.size()>0){
                json = JSONArray.fromObject(list);
            }
        } catch (ServiceException e){
            e.printStackTrace();
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @GetMapping(value = "/getOrderType")
    @ApiOperation(value = "预期到货通知单 查询所有类型为“入库单”的收发类别", response = JSONObject.class, notes = "查询所有类型为“入库单”的收发类别")
    public @ResponseBody
    JSONObject getOrderType(HttpSession session){
        JSONObject json = getJSONObject();
        try {

            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            if(hz.size()>0){
                Map<String,Object> map = baseService.getOrderType(hz.get(0).getHzid());
                json = JSONObject.fromObject(map);
            }
        } catch(ServiceException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @GetMapping(value = "/getInfoByNew/{sscgdid}")
    @ApiOperation(value = "预期到货通知单 新增预期到货通知单获取默认信息", response = JSONObject.class,
            notes = "新增预期到货通知单调用")
    public @ResponseBody
    JSONObject getInfoByNew(HttpSession session,@PathVariable("sscgdid") String sscgdid){
        JSONObject json = getJSONObject();
        try {
            //获取当前用户
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckmc = userinfo.getUser().getOrgName();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
            String asnbh = df.format(new Date())+Integer.toString((int)(Math.random()*9+1)*1000);
            List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            //如果采购订单ID不等于0的情况下查询出来 预计到货时间 jydhsj 供应商编号gysbh
            if(!sscgdid.equals("0")){
                json = JSONObject.fromObject(baseService.getGysAndYjsj(sscgdid));
            }
            if(hz.size()>0){
                json.put("hz",hz.get(0).getShow_hzid());
                WmsOwner wmsOwner = wmsOwnerService.selectById(hz.get(0).getHzid());
                if(wmsOwner != null){
                    json.put("shscscrq",wmsOwner.getShscscrq());
                    json.put("shscpch",wmsOwner.getShscpch());
                }
            }
            //插入默认信息
            json.put("asnbh",asnbh);
            json.put("asnzt",0);
            json.put("yxj",1);
            json.put("zjzt",0);
            json.put("ckmc",ckmc);
            json.put("shzt",0);
            json.put("shr","");
            json.put("dysj","");
            json.put("zdr",userinfo.getUser().getName());
            json.put("dyzt",0);
            json.put("shsj","");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @GetMapping(value = "/getWosByHzid/{hzid}")
    @ApiOperation(value = "预期到货通知单 获取所有当前货主下供应商信息", response = JSONObject.class,
            notes = "{\"hzid\":\"货主ID\"}</br>返回值 id:供应商id，mc:供应商名称，bh:供应商编号")
    public @ResponseBody
    JSONArray getGysByHzid(@PathVariable("hzid") String hzid){
        JSONArray json = new JSONArray();
        try {
            json = JSONArray.fromObject(baseService.getGysByHzid(hzid));
        } catch(ServiceException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @GetMapping(value = "/getHpByHzid/{hzid}")
    @ApiOperation(value = "预期到货通知单 获取所有当前货主下货品信息", response = JSONObject.class,
            notes = "{\"hzid\":\"货主ID\"}</br>返回值 id:货品id，mc:货品名称，bh:货品编号")
    public @ResponseBody
    JSONArray getHpByHzid(@PathVariable("hzid") String hzid){
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        try {
            list = baseService.getHpByHzid(hzid);
        } catch(ServiceException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONArray.fromObject(list);
    }

    @ApiOperation(value = "预期到货通知单 新增预期到货通知单",response = JSONObject.class, notes = "POST请求新增预期到货通知单")
    @PostMapping(value = "/add")
    public @ResponseBody
    JSONObject add(HttpSession session,@RequestBody WmsEstimatedArrivalOrder entity){
        try {
            entity.setId(UUIDUtils.uuid());
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            if(hz.size()>0){
                entity.setHzid(hz.get(0).getHzid());
            }else{
                entity.setHzid("0");
            }
            //加入新增预期到货通知到的默认参数
            entity.setZdr(userinfo.getUser().getName());
            entity.setCkid(String.valueOf(userinfo.getUser().getOrgId().get(0)));
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            entity.setZdr(userinfo.getUser().getName());
            entity.setCjsj(sdf.format(new Date()));
            entity.setYjdhsjjs(sdf.format(new Date(Long.valueOf(entity.getYjdhsjjs()))));
            entity.setYjdhsjks(sdf.format(new Date(Long.valueOf(entity.getYjdhsjks()))));
            entity.setXgr(userinfo.getUser().getName());
            entity.setXgsj(sdf.format(new Date()));
            entity.setCkid(String.valueOf(userinfo.getUser().getOrgId().get(0)));
            entity.setAsnzt("0");
            baseService.baseInsertSelective(entity);
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"新增预期到货通知单成功","", JSONObject.fromObject(entity).toString());
        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"新增预期到货通知单失败",e.getMessage(),"");
        } catch (SucessException e) {
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"新增预期到货通知单成功","", JSONObject.fromObject(entity).toString());
        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"新增预期到货通知单失败",e.getMessage(),"");
        }
    }

    @ApiOperation(value = "预期到货通知单 修改预期到货通知单",response = JSONObject.class, notes = "POST请求修改预期到货通知单")
    @PutMapping(value = "/edit")
    public @ResponseBody
    JSONObject edit(HttpSession session,@RequestBody WmsEstimatedArrivalOrder entity){
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            entity.setXgr(userinfo.getUser().getName());
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            entity.setXgsj(sdf.format(new Date()));
            if(entity.getYjdhsjjs() != null){
                entity.setYjdhsjjs(sdf.format(new Date(Long.valueOf(entity.getYjdhsjjs()))));
            }
            if(entity.getYjdhsjks() != null){
                entity.setYjdhsjks(sdf.format(new Date(Long.valueOf(entity.getYjdhsjks()))));
            }
            baseService.baseUpdateByPrimaryKeySelective(entity);
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"修改预期到货通知单成功","", "");
        }catch (SucessException e){
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"修改预期到货通知单成功",e.getMessage(), "");
        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"修改预期到货通知单失败",e.getMessage(),"");
        } catch (Exception e){
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"修改预期到货通知单失败",e.getMessage(),"");
        }
    }

    @PostMapping(value = "/auditing")
    @ApiOperation(value = "预期到货通知单 审核", response = JSONObject.class,
            notes = "审核 ids表示ASN id")
    public @ResponseBody
    JSONObject auditing(HttpSession session,@RequestBody SetAndModifyModel setAndModifyModel){
        try{
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            baseService.auditing(setAndModifyModel,userinfo.getUser().getName());
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"审核成功","", "");
        } catch(ServiceException e){
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"审核失败",e.getMessage(),"");
        } catch (SucessException e){
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"审核成功",e.getMessage(), "");
        } catch(Exception e){
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"审核失败",e.getMessage(),"");
        }
    }

    @PostMapping(value = "/fulfil")
    @ApiOperation(value = "预期到货通知单 收货完成", response = JSONObject.class,
            notes = "收货完成 ids表示ASN id")
    public @ResponseBody
    JSONObject fulfil(HttpSession session,@RequestBody SetAndModifyModel setAndModifyModel){
        try{
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            baseService.fulfil(setAndModifyModel,userinfo.getUser().getName());
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"收货完成","", "");
        } catch(SucessException e){
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"收货完成","", "");
        } catch(ServiceException e){
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"收货完成失败",e.getMessage(),"");
        } catch(Exception e){
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"收货完成失败",e.getMessage(),"");
        }
    }

    @PostMapping(value = "/del")
    @ApiOperation(value = "预期到货通知单 作废", response = JSONObject.class,
            notes = "作废预期到货通知单")
    public @ResponseBody
    JSONObject del(HttpSession session,@RequestBody SetAndModifyModel setAndModifyModel) {
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            baseService.del(setAndModifyModel,userinfo.getUser().getName());
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"作废成功","", "");
        } catch (SucessException e) {
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"作废成功",e.getMessage(), "");
        } catch (ServiceException e) {
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"作废失败",e.getMessage(),"");
        }  catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"作废失败",e.getMessage(),"");
        }
    }

    @PostMapping(value = "/getBill")
    @ApiOperation(value = "预期到货通知单 生成质检单", response = JSONObject.class, notes = "生成质检单")
    public @ResponseBody
    JSONObject getBill(HttpSession session,@RequestBody SetAndModifyModel setAndModifyModel){
        try {
            String sshzid = "";
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            if(hz.size()>0){
                sshzid = hz.get(0).getHzid();
            }
            baseService.getBill(setAndModifyModel,sshzid,String.valueOf(userinfo.getUser().getOrgId().get(0)));
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"生成质检单成功","", "");
        } catch (SucessException e) {
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.success.toString(),"生成质检单成功",e.getMessage(), "");
        } catch (ServiceException e){
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.error.toString(),"生成质检单失败",e.getMessage(), "");
        } catch (Exception e){
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(),ReturnType.error.toString(),"生成质检单失败",e.getMessage(), "");
        }
    }

    @PostMapping(value = "/print")
    @ApiOperation(value = "预期到货通知单 打印", response = JSONObject.class, notes = "打印")
    public @ResponseBody
    JSONArray print(HttpSession session,@RequestBody SetAndModifyModel setAndModifyModel){
        JSONArray json = new JSONArray();
        try {
            String host = PropertyUtil.getProperty("safety.host");
            String port = PropertyUtil.getProperty("safety.port");
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("list",setAndModifyModel.getIds());
            if(hz.size()>0){
                map.put("hzmc",hz.get(0).getShow_hzid());
            }
            String result = HttpUtil.doGet("http://"+host+":"+port+"/ms-safety/org/getOrgInfo/"+String.valueOf(userinfo.getUser().getOrgId().get(0)),session.getId());
            map.put("ckdz",JSONObject.fromObject(result).get("address"));
            json = JSONArray.fromObject(baseService.print(map));
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return json;
    }

}
